/**
 * 用户管理路由
 * User Management Routes
 */

const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();

const User = require('../database/models/User');
const { adminMiddleware } = require('../middleware/auth');
const authService = require('../services/AuthService');
const logger = require('../utils/logger');

/**
 * 获取用户信息
 * GET /api/user/profile
 */
router.get('/profile', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    // 获取用户详细信息
    const user = await User.findById(userId, 'id, email, nickname, role, avatar, storage_used, storage_limit, last_login_at, created_at');
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在 / User not found'
      });
    }

    // 获取存储统计
    const storageStats = await User.getStorageStats(userId);

    res.json({
      success: true,
      message: '获取用户信息成功 / Get user profile successful',
      user: {
        ...user,
        storageStats
      }
    });

  } catch (error) {
    logger.error('获取用户信息失败 / Failed to get user profile', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 更新用户信息
 * PUT /api/user/profile
 */
router.put('/profile', 
  [
    body('nickname')
      .optional()
      .isLength({ min: 1, max: 50 })
      .withMessage('昵称长度必须在1-50字符之间 / Nickname must be 1-50 characters'),
    body('email')
      .optional()
      .isEmail()
      .normalizeEmail()
      .withMessage('请输入有效的邮箱地址 / Please enter a valid email address')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { nickname, email } = req.body;

      const updateData = {};
      
      if (nickname !== undefined) {
        updateData.nickname = nickname;
      }
      
      if (email !== undefined) {
        // 检查邮箱是否已被其他用户使用
        const existingUser = await User.findByEmail(email);
        if (existingUser && existingUser.id !== userId) {
          return res.status(409).json({
            success: false,
            message: '邮箱已被其他用户使用 / Email already used by another user'
          });
        }
        updateData.email = email;
      }

      if (Object.keys(updateData).length === 0) {
        return res.status(400).json({
          success: false,
          message: '没有提供要更新的数据 / No data provided for update'
        });
      }

      // 更新用户信息
      const updatedUser = await User.update(userId, updateData);

      logger.info('用户信息更新成功 / User profile updated successfully', {
        userId,
        updatedFields: Object.keys(updateData)
      });

      res.json({
        success: true,
        message: '用户信息更新成功 / User profile updated successfully',
        user: {
          id: updatedUser.id,
          email: updatedUser.email,
          nickname: updatedUser.nickname,
          role: updatedUser.role,
          avatar: updatedUser.avatar
        }
      });

    } catch (error) {
      logger.error('更新用户信息失败 / Failed to update user profile', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 更新用户密码
 * PUT /api/user/password
 */
router.put('/password',
  [
    body('currentPassword')
      .notEmpty()
      .withMessage('请输入当前密码 / Please enter current password'),
    body('newPassword')
      .isLength({ min: 6 })
      .withMessage('新密码至少6位字符 / New password must be at least 6 characters'),
    body('confirmPassword')
      .custom((value, { req }) => {
        if (value !== req.body.newPassword) {
          throw new Error('确认密码不匹配 / Confirm password does not match');
        }
        return true;
      })
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId, email } = req.user;
      const { currentPassword, newPassword } = req.body;

      // 验证当前密码
      const user = await User.validatePassword(email, currentPassword);
      if (!user) {
        return res.status(401).json({
          success: false,
          message: '当前密码错误 / Current password is incorrect'
        });
      }

      // 验证新密码强度
      const passwordValidation = authService.validatePasswordStrength(newPassword);
      if (!passwordValidation.isValid) {
        return res.status(400).json({
          success: false,
          message: '密码强度不足 / Password strength insufficient',
          errors: passwordValidation.errors
        });
      }

      // 更新密码
      await User.updatePassword(userId, newPassword);

      logger.info('用户密码更新成功 / User password updated successfully', {
        userId,
        email
      });

      res.json({
        success: true,
        message: '密码更新成功 / Password updated successfully'
      });

    } catch (error) {
      logger.error('更新用户密码失败 / Failed to update user password', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);/**

 * 管理员创建用户
 * POST /api/user/admin/users
 */
router.post('/admin/users', 
  adminMiddleware,
  [
    body('email')
      .isEmail()
      .normalizeEmail()
      .withMessage('请输入有效的邮箱地址 / Please enter a valid email address'),
    body('password')
      .isLength({ min: 6 })
      .withMessage('密码至少6位字符 / Password must be at least 6 characters'),
    body('nickname')
      .isLength({ min: 1, max: 50 })
      .withMessage('昵称长度必须在1-50字符之间 / Nickname must be 1-50 characters'),
    body('role')
      .optional()
      .isIn(['user', 'admin'])
      .withMessage('角色必须是user或admin / Role must be user or admin'),
    body('storage_limit')
      .optional()
      .isInt({ min: 0 })
      .withMessage('存储限制必须是非负整数 / Storage limit must be a non-negative integer')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { email, password, nickname, role = 'user', storage_limit } = req.body;
      const adminUserId = req.user.id;

      // 验证密码强度
      const passwordValidation = authService.validatePasswordStrength(password);
      if (!passwordValidation.isValid) {
        return res.status(400).json({
          success: false,
          message: '密码强度不足 / Password strength insufficient',
          errors: passwordValidation.errors,
          strength: passwordValidation.strength
        });
      }

      // 创建用户数据
      const userData = {
        email,
        password,
        nickname,
        role,
        storage_limit: storage_limit || undefined // 使用默认值
      };

      // 创建用户
      const newUser = await User.createUser(userData);

      logger.info('管理员创建用户成功 / Admin created user successfully', {
        adminUserId,
        newUserId: newUser.id,
        newUserEmail: newUser.email,
        newUserRole: newUser.role
      });

      res.status(201).json({
        success: true,
        message: '用户创建成功 / User created successfully',
        user: {
          id: newUser.id,
          email: newUser.email,
          nickname: newUser.nickname,
          role: newUser.role,
          storage_limit: newUser.storage_limit,
          created_at: newUser.created_at
        }
      });

    } catch (error) {
      logger.error('管理员创建用户失败 / Admin failed to create user', {
        adminUserId: req.user?.id,
        email: req.body.email,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 管理员获取用户列表
 * GET /api/user/admin/users
 */
router.get('/admin/users', 
  adminMiddleware,
  async (req, res, next) => {
    try {
      const { page = 1, pageSize = 20, search = '', role = '' } = req.query;

      let users;
      
      if (search) {
        // 搜索用户
        users = await User.searchUsers(search, {
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        });
      } else {
        // 获取用户列表
        const conditions = {};
        if (role) {
          conditions.role = role;
        }

        users = await User.paginate(conditions, {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          fields: 'id, email, nickname, role, is_active, storage_used, storage_limit, last_login_at, created_at',
          orderBy: 'created_at DESC'
        });
      }

      res.json({
        success: true,
        message: '获取用户列表成功 / Get users list successful',
        ...users
      });

    } catch (error) {
      logger.error('管理员获取用户列表失败 / Admin failed to get users list', {
        adminUserId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 管理员获取用户详情
 * GET /api/user/admin/users/:userId
 */
router.get('/admin/users/:userId', 
  adminMiddleware,
  async (req, res, next) => {
    try {
      const { userId } = req.params;

      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在 / User not found'
        });
      }

      // 获取用户存储统计
      const storageStats = await User.getStorageStats(userId);

      // 移除敏感信息
      delete user.password;

      res.json({
        success: true,
        message: '获取用户详情成功 / Get user details successful',
        user: {
          ...user,
          storageStats
        }
      });

    } catch (error) {
      logger.error('管理员获取用户详情失败 / Admin failed to get user details', {
        adminUserId: req.user?.id,
        targetUserId: req.params.userId,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 管理员更新用户信息
 * PUT /api/user/admin/users/:userId
 */
router.put('/admin/users/:userId', 
  adminMiddleware,
  [
    body('nickname')
      .optional()
      .isLength({ min: 1, max: 50 })
      .withMessage('昵称长度必须在1-50字符之间 / Nickname must be 1-50 characters'),
    body('role')
      .optional()
      .isIn(['user', 'admin'])
      .withMessage('角色必须是user或admin / Role must be user or admin'),
    body('is_active')
      .optional()
      .isBoolean()
      .withMessage('账户状态必须是布尔值 / Account status must be boolean'),
    body('storage_limit')
      .optional()
      .isInt({ min: 0 })
      .withMessage('存储限制必须是非负整数 / Storage limit must be a non-negative integer')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { userId } = req.params;
      const { nickname, role, is_active, storage_limit } = req.body;
      const adminUserId = req.user.id;

      // 检查目标用户是否存在
      const targetUser = await User.findById(userId);
      if (!targetUser) {
        return res.status(404).json({
          success: false,
          message: '用户不存在 / User not found'
        });
      }

      // 防止管理员修改自己的角色或状态
      if (userId == adminUserId && (role !== undefined || is_active !== undefined)) {
        return res.status(403).json({
          success: false,
          message: '不能修改自己的角色或账户状态 / Cannot modify your own role or account status'
        });
      }

      const updateData = {};
      
      if (nickname !== undefined) updateData.nickname = nickname;
      if (role !== undefined) updateData.role = role;
      if (is_active !== undefined) updateData.is_active = is_active ? 1 : 0;
      if (storage_limit !== undefined) updateData.storage_limit = storage_limit;

      if (Object.keys(updateData).length === 0) {
        return res.status(400).json({
          success: false,
          message: '没有提供要更新的数据 / No data provided for update'
        });
      }

      // 更新用户信息
      const updatedUser = await User.update(userId, updateData);

      logger.info('管理员更新用户信息成功 / Admin updated user successfully', {
        adminUserId,
        targetUserId: userId,
        updatedFields: Object.keys(updateData)
      });

      // 移除敏感信息
      delete updatedUser.password;

      res.json({
        success: true,
        message: '用户信息更新成功 / User updated successfully',
        user: updatedUser
      });

    } catch (error) {
      logger.error('管理员更新用户信息失败 / Admin failed to update user', {
        adminUserId: req.user?.id,
        targetUserId: req.params.userId,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 管理员禁用/启用用户
 * POST /api/user/admin/users/:userId/toggle-status
 */
router.post('/admin/users/:userId/toggle-status', 
  adminMiddleware,
  async (req, res, next) => {
    try {
      const { userId } = req.params;
      const adminUserId = req.user.id;

      // 防止管理员禁用自己
      if (userId == adminUserId) {
        return res.status(403).json({
          success: false,
          message: '不能禁用自己的账户 / Cannot disable your own account'
        });
      }

      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在 / User not found'
        });
      }

      const newStatus = !user.is_active;
      const action = newStatus ? 'enable' : 'disable';

      if (newStatus) {
        await User.enableUser(userId);
      } else {
        await User.disableUser(userId);
      }

      logger.info(`管理员${action}用户成功 / Admin ${action}d user successfully`, {
        adminUserId,
        targetUserId: userId,
        newStatus
      });

      res.json({
        success: true,
        message: `用户账户已${newStatus ? '启用' : '禁用'} / User account ${newStatus ? 'enabled' : 'disabled'}`,
        user: {
          id: user.id,
          email: user.email,
          is_active: newStatus
        }
      });

    } catch (error) {
      logger.error('管理员切换用户状态失败 / Admin failed to toggle user status', {
        adminUserId: req.user?.id,
        targetUserId: req.params.userId,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 管理员获取用户统计
 * GET /api/user/admin/stats
 */
router.get('/admin/stats', 
  adminMiddleware,
  async (req, res, next) => {
    try {
      const stats = await User.getUserStats();

      res.json({
        success: true,
        message: '获取用户统计成功 / Get user statistics successful',
        stats
      });

    } catch (error) {
      logger.error('管理员获取用户统计失败 / Admin failed to get user statistics', {
        adminUserId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

module.exports = router;